//
//  StoreDetailsViewController.m
//  iFoundIt
//
//  Created by Navid Shariat on 4/05/10.
//  Copyright 2010 QUT. All rights reserved.
//

#import "StoreDetailsViewController.h"
#import "SystemAnnotation.h"

@implementation StoreDetailsViewController

@synthesize store;
@synthesize nameLabel;
@synthesize addLabel;
@synthesize distLabel;
@synthesize mapView;
//@synthesize reverseGeocoder;
@synthesize locationManager;

const NSString * CurrentLocationAnnotTitle=@"Your Location";
const NSString * StoreLocationAnnotTitle=@"Store Location";
const int CurrentLocColor= MKPinAnnotationColorPurple;
const int StoreLocColor= MKPinAnnotationColorRed;

- (void)dealloc {
	[ store	release];
	[ nameLabel release];
	[ addLabel release];
	[ distLabel release];
	[mapView release];
	[CurrentLocationAnnotTitle release];
	[StoreLocationAnnotTitle release];
    [super dealloc];
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
//    mapView.showsUserLocation = YES;	
	self.navigationItem.backBarButtonItem.enabled = NO;
	CLLocationManager *locMan = [[CLLocationManager alloc] init];
	[locMan setDelegate:self];
	[locMan setDistanceFilter:10.0f];
	[locMan setDesiredAccuracy:kCLLocationAccuracyBest];
	[self setLocationManager:locMan];
	[locMan release];
 
 // Once configured, the location manager must be "started".
	[[self locationManager] startUpdatingLocation];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark actions

 - (IBAction)reverseGeocodeCurrentLocation{
/*    self.reverseGeocoder =
	[[[MKReverseGeocoder alloc] initWithCoordinate:mapView.userLocation.location.coordinate] autorelease];
    reverseGeocoder.delegate = self;
    [reverseGeocoder start];	*/
}

#pragma mark mapDelegates

- (MKAnnotationView *)mapView:(MKMapView *)mapViewa viewForAnnotation:(id <MKAnnotation>)annotation {
	NSLog(@">> viewForAnnotation");
	
	// if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
		return nil;
	}
	
	
	// if this is annoation is a system annotation
	if ([annotation isKindOfClass:[SystemAnnotation class]]) {
		
		// try to dequeue an existing pin view first
        static NSString *SystemAnnotationIdentifier = @"SystemAnnotationIdentifier";
        MKPinAnnotationView *oldPinAnnotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:SystemAnnotationIdentifier];
		
		// if an existing pin view was not available
		if (!oldPinAnnotationView) {
			
			// create one
			MKPinAnnotationView *pinAnnotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:SystemAnnotationIdentifier];
			if ([annotation title] == CurrentLocationAnnotTitle)
				[pinAnnotationView setPinColor: CurrentLocColor];			
			else {
				[pinAnnotationView setPinColor: StoreLocColor];							
			}

			[pinAnnotationView setCanShowCallout:YES];
			[pinAnnotationView setSelected:YES];
			[pinAnnotationView setAnimatesDrop:YES];
			
//			UIButton *rightAccessoryButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
//			[rightAccessoryButton addTarget:self action:@selector(rightAccessoryAddButtonClicked) forControlEvents:UIControlEventTouchUpInside];			 			
//			[pinAnnotationView setRightCalloutAccessoryView:rightAccessoryButton];
			// return the new pinannotationview
			return pinAnnotationView;
			
		} else { // if there is an old pin
			
			// assign the annotation to the old pinview
			[oldPinAnnotationView setAnnotation:annotation];
			
			// return the old pinannotationview
			return oldPinAnnotationView;
		}
		
	}
	
	return nil;
}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
    // we have received our current location, so enable the "Get Current Address" button
//    [getAddressButton setEnabled:YES];	
	for(MKAnnotationView *annotationView in views) {
		if(annotationView.annotation == mapView.userLocation) {
			MKCoordinateRegion newRegion=[self createRegion];
			// zoom to this location
			[mapView setRegion:newRegion animated:YES];
//			newRegion=[mapView regionThatFits:newRegion];
//			[mapView setRegion:newRegion animated:TRUE];
			
			//[self performSelector:@selector(dropPinToCurrentLocation) withObject:nil afterDelay:1.0];
//			[storeLoc release];
		}
	}
}

- (MKCoordinateRegion) createRegion{
	CLLocationCoordinate2D userLocation = mapView.userLocation.coordinate;	
	CLLocationCoordinate2D stCoordinate=[[self store] getCoordinate];
	CLLocationCoordinate2D location;	
	double latDelta=userLocation.latitude-stCoordinate.latitude;
	double longDelta=userLocation.longitude-stCoordinate.longitude;
	latDelta= (latDelta>=0?latDelta: latDelta-(2*latDelta));
	longDelta= (longDelta>=0?longDelta: longDelta-(2*longDelta));

	location.latitude=(double)(userLocation.latitude+stCoordinate.latitude)/2;
	location.longitude=(double)(userLocation.longitude+stCoordinate.longitude)/2;
	// get current location
	
	MKCoordinateRegion newRegion;
	newRegion.center = location;
	newRegion.span.latitudeDelta = latDelta+(latDelta*0.1);
	newRegion.span.longitudeDelta =longDelta+(longDelta*0.1); 
	return newRegion;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
	NSLog(@"calloutAccessoryControlTapped");
}

#pragma mark locationDelegates
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	NSLog(@"didUpdateToLocation2");	
	[manager stopUpdatingLocation];
	CLLocationCoordinate2D cd=[[[self mapView] userLocation] coordinate];
	[self dropPinToCurrentLocation: cd];		
	cd.latitude=[[self store] latitude];
	cd.longitude=[[self store] longtitude];
	[self dropPinToCurrentLocation: cd];		
}	

#pragma mark rgeocoderDelegate
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
	NSLog(@"didFindPlacemark");
	NSMutableString *locationAddress = [[NSMutableString alloc] init];
	
	if ([[placemark subThoroughfare] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.subThoroughfare];
	}
	
	if ([[placemark thoroughfare] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.thoroughfare];
	}
	
	if ([[placemark subLocality] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.subLocality];
	}
	
	if ([[placemark locality] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.locality];
	}
	// create a new annotation
	SystemAnnotation *systemAnnotation = [[SystemAnnotation alloc] init];
	if ([self areTheSamePlace: [placemark coordinate]: [store getCoordinate]]){
		[systemAnnotation setAnnotationTitle: [NSString stringWithFormat:@"%@", [store  shopName]]];
		[systemAnnotation setAnnotationSubtitle:[NSString stringWithFormat:@"%@, Dist: %.2lfKm",locationAddress, ([store distance]/1000)]];
	}
	else
	{
		[systemAnnotation setAnnotationTitle:CurrentLocationAnnotTitle];							
		[systemAnnotation setAnnotationSubtitle:[NSString stringWithString:locationAddress]];
	}
//	[systemAnnotation setAnnotationCoordinate:[[[self mapView] userLocation] coordinate]];
	[systemAnnotation setAnnotationCoordinate:[placemark coordinate]];
	// add this annotation to the map
	[[self mapView] addAnnotation:systemAnnotation];
	[systemAnnotation release];
	// release string
	[locationAddress release];	
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
	NSLog(@"reverseGeocoder:didFailWithError");
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
													message:@"Unable to determine your location."
												   delegate:nil
										  cancelButtonTitle:@"OK" 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}

#pragma mark methods
- (void)dropPinToCurrentLocation: (CLLocationCoordinate2D) coordinate {
//	MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[[[self mapView] userLocation] coordinate]];
	MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate: coordinate];
	[reverseGeocoder setDelegate:self];
	[reverseGeocoder start];	
}

- (BOOL) areTheSamePlace: (CLLocationCoordinate2D) co1: (CLLocationCoordinate2D) co2{
	if (co1.latitude==co2.latitude && co1.longitude==co2.longitude )
		return YES;
	return NO;
}

@end
